#define _CRT_SECURE_NO_WARNINGS 1

#include"LinkedList.h"
////
Node* CreateNode(Datatype x)
{
	Node* newnode = (Node*)malloc(sizeof(Node));
	if (newnode == NULL)
	{
		perror("CreateNode:malloc failed");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;

	return newnode;
}

void LLPushBack(Node** tail, Datatype x)
{
	Node* newnode = CreateNode(x);

	(*tail)->next = newnode;
	*tail = newnode;
} 

void LLPushFront(Node** head, Datatype x)
{
	Node* newnode = CreateNode(x);

	newnode->next = (*head)->next;
	(*head)->next = newnode;
}

void LLPopBack(Node** head)
{
	Node* p = *head;

	assert((*head)->next != NULL);

	while (p->next->next != NULL)
	{
		p = p->next;
	}

	free(p->next);
	p->next = NULL;
}

void LLPopFront(Node** head)
{
	Node* p = (*head)->next;
	Node* prev = p;

	assert((*head)->next != NULL);

	(*head)->next = (*head)->next->next;
	free(prev);
}

void LLPrint(Node** head)
{	
	Node* p = *head;
	
	//skip head
	p = p->next;
	
	while(p != NULL)
	{
		printf("%d->", p->data);
		p = p->next;
	}
	printf("NULL\n");
}

Node* LLFind(Node* head, Datatype x)
{
	Node* p = head;
	while (p != NULL)
	{
		if (p->data == x)
		{
			return p;
		}
		p = p->next;
	}

	return NULL;
}

void LLInsert(Node** head, Datatype x, Node* pos)
{
	assert(head != NULL);
	assert(pos != NULL);

	Node* p = *head;
	while (p->next != pos)
	{
		p = p->next;
	}

	Node* newnode = CreateNode(x);

	newnode->next = p->next;
	p->next = newnode;
}

void LLErase(Node** head, Node* pos)
{
	assert(head != NULL);
	assert(pos != NULL);
	
	Node* p = *head;
	while (p->next != pos)
	{
		p = p->next;
	}
	
	p->next = pos->next;
	free(pos);
	pos = NULL;
}

void LLModify(Datatype x, Node* pos)
{
	pos->data = x;
}